import os
import sys

import time

CELERY_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(CELERY_BASE_DIR, '../meiduo_mall'))
from celery import Celery
# 定义celery实例,需要参数:实例名,任务发布位置,结果保存位置

app = Celery('mycelery', broker='redis://127.0.0.1:6379/14', backend='redis://127.0.0.1:6379/15')


# @app.task
# def add(x,y):
#     return x+y

@app.task(bind=True)
def send_sms_code(self,mobile, sms_code, time_expire):
    from libs.yuntongxun.sms import CCP
    time.sleep(5)
    ccp = CCP()
    try:
        # 用res接受发送结果,成功为0,失败为-1
        res = ccp.send_template_sms(mobile, [sms_code, time_expire], 1)
    except Exception as e:
        print(e)
        res = -1
    if res == -1:
        # res如果是-1,即发送失败,重试
        self.retry(contdown=5,max_retries=3,exc=Exception('短信发送失败'))
@app.task(bind=True)
def send_email_code(self,title,check_code,from_email,to_email):
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo_mall.dev")
    import django
    django.setup()
    from django.core.mail import send_mail
    #         send_mail(subject='测试邮件', message='这是测试邮件', from_email=settings.EMAIL_FROM, recipient_list=[user.email])
    email = [to_email]
    info = send_mail(subject=title,message=check_code,from_email=from_email,recipient_list=email)

    if info == 0:
        self.retry(countdown=5, max_retries=3, exc=Exception('邮箱验证发送失败'))
    else:
        return info
